<?php

namespace app\forms\user;

use app\forms\Model;
use app\models\User;
use yii\db\Exception;
use yii\web\HttpException;
use app\validators\PositiveInteger;

class GrantForm extends Model
{
    public $id;

    public $item;
    public $auth;
    public $data;

    public function rules()
    {
        return [
            ['id', PositiveInteger::class],
            ['id', 'required'],
            ['id', 'exist', 'targetClass' => User::class],

            ['item', 'safe'],
            ['auth', 'safe'],
        ];
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function grant($param)
    {
        $form = new self;
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $user = User::findOne($form['id']);
            $user->removeItem();
            $user->addItem($form['item'], $form['auth'], $form['data']);
        } catch (Exception $e) {
            $form->serverError();
        }
        $form->updateOk();
    }
}